<?php


namespace app\api\controller\wechat;

use app\BaseController;
use app\Request;
use app\models\user\WechatUser;
use app\models\user\UserToken;
use learn\services\UtilService;
use think\facade\Db;
use app\models\user\User;
use learn\services\MiniProgramService;

/**
 * Class WechatController
 * @package app\api\controller\wechat
 */
class AppletsController extends BaseController
{
    //登录&&注册
    public function toLogin(Request $request)
    {
        //判断小程序
        list($encryptedData,$session_key,$iv) = UtilService::postMore([['encryptedData',''],['session_key',''],['iv','']],$request, true);
        
        $uid = 0;
        
        
        
        if ($encryptedData != "" && $session_key != "" && $iv != "") {
            $wechat = MiniProgramService::encryptor($session_key,$iv,$encryptedData);
            // halt($wechat);
        }else{
            return app('json')->fail('登录失败');
        }
        
        
        
        
        if (WechatUser::UserHas($wechat['openId'])) {
            
            $data = [
                "create_time" => time(),
                'status'      => 1,
                'login_type'  => 1,
                "edit_time"   => time(),
                "password"    => md5(111111),
                "account"     => $wechat['openId'],
                'card_number' => $this->membershipCard()
            ];
            
            $uid = Db::name("user")->insertGetId($data);
            //创建微信用户
            $wechatList = [
                "uid"        => $uid,
                'openid'     => $wechat['openId'],
                "nickname"   => $wechat['nickName'],
                "avatar"     => $wechat['avatarUrl'],
                "city"       => $wechat['city'],
                "language"   => $wechat['language'],
                "province"   => $wechat['province'],
                'country'    => $wechat['country'],
                'add_time'   => time(),
            ];
            if (isset($wechat['unionId'])){
                $wechatList['unionid'] = $wechat['unionId'];
            }
            WechatUser::create($wechatList);
        }else{
            //有用户 更新
            $wechatList = [
                "nickname"   => $wechat['nickName'],
                "avatar"     => $wechat['avatarUrl'],
                "city"       => $wechat['city'],
                "language"   => $wechat['language'],
                "province"   => $wechat['province'],
                'country'    => $wechat['country'],
            ];
            if (isset($wechat['unionId'])){
                $wechatList['unionid'] = $wechat['unionId'];
            }
            WechatUser::where("openid",$wechat['openId'])->update($wechatList);
            $uid = WechatUser::where("openid",$wechat['openId'])->value("uid");
        }
        
        
        $userInfo = User::alias("u")
        ->join("wechat_user w","u.uid = w.uid")
        ->where("w.uid",$uid)
        ->field("u.uid,u.integral,w.nickname,w.avatar,u.card_number")
        ->find()->toArray();
        $times = strtotime("+ 5000hour");
        $token = UserToken::tokenCreate($uid,$times);
        if ($token) {
            return app('json')->success('登录成功', ['token' => $token, 'expires_time' => $times,'userInfo'=>$userInfo]);
        } else
            return app('json')->fail('登录失败');
    }

}